﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.IO;
using kensei.notify;

namespace Meerkat_Service
{
    public partial class Core : ServiceBase
    {
        private Config c = new Config();
        private DateTime DoNotSendUntilAfter;
        private Thread workerThread;

        private kensei.notify.WindowsEventLog notify = new kensei.notify.WindowsEventLog();

        public Core()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            c.LoadConfig();
            workerThread = new Thread(new ThreadStart(MonitorDisks));
            workerThread.Name = "workerThread";
            workerThread.Start();
        }

        private void MonitorDisks()
        {
            bool SuppressAlerts = false;

            for (; ; )
            {
                if (DoNotSendUntilAfter != null)
                {
                    TimeSpan ts = DateTime.Now - DoNotSendUntilAfter;
                    if (ts.TotalSeconds > 0)
                    {
                        SuppressAlerts = false;
                    }
                    else
                    {
                        SuppressAlerts = true;
                    }
                }
                else
                {
                    SuppressAlerts = false;
                }

                if (!SuppressAlerts)
                {
                    //notify.WriteEvent("Meerkat", "Checking disks...", kensei.notify.WindowsEventLog.LogEntryType.Information);
                    DriveInfo[] allDrives = DriveInfo.GetDrives();
                    foreach (DriveInfo dirInfo in allDrives)
                    {
                        try
                        {
                            if (dirInfo.IsReady && c.DisksToMonitor.Contains(dirInfo.Name.Replace(@":\", "")) == true)
                            {
                                //notify.WriteEvent("Meerkat", "Disk " + dirInfo.Name.Replace(@":\", "") + " [free space:" + dirInfo.TotalFreeSpace.ToString() + ", threshold: " + Utils.ConvertToBytes(c.ThresholdAmount, c.ThresholdUnit).ToString() + "]", kensei.notify.WindowsEventLog.LogEntryType.Information);
                                if (dirInfo.TotalFreeSpace < Utils.ConvertToBytes(c.ThresholdAmount, c.ThresholdUnit))
                                {
                                    //notify.WriteEvent("Meerkat", "Threshold reached, sending alert...", kensei.notify.WindowsEventLog.LogEntryType.Information);
                                    SendAlerts(dirInfo.Name.Replace(@"\", ""), c.ThresholdAmount.ToString(), c.ThresholdUnit);
                                }
                            }
                        }
                        catch { }
                    }
                }

                System.Threading.Thread.Sleep(System.TimeSpan.FromMinutes(5));
            }
        }

        private void SendAlerts(string Drive, string ThesholdAmount, string ThresholdUnit)
        {
            DoNotSendUntilAfter = DateTime.Now.AddMinutes(c.EmailDelay);

            foreach (string s in c.EmailAddresses)
            {
                if (!string.IsNullOrEmpty(c.SmtpServerUsername) && !string.IsNullOrEmpty(c.SmtpServerPassword))
                {
                    kensei.notify.Email.Send(c.SendFrom, "", s, "", "", "", "Warning! Disk space is low on " + c.MachineName, "<p style='font-family:helvetica,arial,sans-serif;font-size:83%;'>Disk space is low on " + c.MachineName + "<br/>Free space on " + Drive + " is less than " + ThesholdAmount + " " + ThresholdUnit + "<br/><br/><small>This is an automated email generated by Meerkat</small></p>", true, true, c.SmtpServer, Convert.ToInt32(c.SmtpServerPort), c.SmtpServerUsername, c.SmtpServerPassword);
                }
                else
                {
                    kensei.notify.Email.Send(c.SendFrom, "", s, "", "", "", "Warning! Disk space is low on " + c.MachineName, "<p style='font-family:helvetica,arial,sans-serif;font-size:83%;'>Disk space is low on " + c.MachineName + "<br/>Free space on " + Drive + " is less than " + ThesholdAmount + " " + ThresholdUnit + "<br/><br/><small>This is an automated email generated by Meerkat</small></p>", true, true, c.SmtpServer, 25, "", "");
                }
            }
        }

        protected override void OnStop()
        {
            workerThread.Abort();
        }

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
#if DEBUG
            Core DebugService = new Core();
            DebugService.OnStart(null);
#else
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
			{ 
				new Core() 
			};
            ServiceBase.Run(ServicesToRun);
#endif
        }
    }
}
